// DOM元素
const followBtn = document.getElementById('followBtn');
const followStatus = document.getElementById('followStatus');
const notesList = document.getElementById('notesList');
const noteCount = document.getElementById('noteCount');
const followerCount = document.getElementById('followerCount');
const followingCount = document.getElementById('followingCount');

// 初始化页面
async function initPage() {
    //获取参数
    const params = new URLSearchParams(window.location.search);
    const uid = params.get('uid');
    // console.log(uid);

    //发送请求
    const data = await fetch(`http://localhost/api/user/getProfile?uid=${uid}`, {
        mode: 'cors', // 明确请求模式
        headers: {
            'Content-Type': 'application/json'
        }
    })
        .then(response => response.json())
        .then(data => {
            // console.log(data);
            return data.data;
        }
        )
        .catch(error => console.error('Error:', error));
    userData = data;

    //名字
    let un = document.getElementsByClassName('username')[0]
    un.innerHTML = uid;

    // 更新用户数据
    noteCount.textContent = userData.stats.notes;
    followerCount.textContent = userData.stats.followers;
    followingCount.textContent = userData.stats.following;

    //获取头像标签
    const avatar = document.getElementsByClassName('avatar')[0]
    // console.log(avatar);
    avatar.src = userData.avatar;

    // 设置关注按钮状态
    updateFollowButton();

    // 渲染笔记列表
    renderNotes();
}

// 更新关注按钮状态
async function updateFollowButton() {
    //获取参数
    const params = new URLSearchParams(window.location.search);
    const uid = params.get('uid');

    if (userData.isFollowing) {
        followBtn.textContent = '已关注';
        followBtn.classList.add('following');

        // 检查是否是互相关注
        if (userData.isFollowedBack) {
            // followStatus.textContent = '你们互相关注';
            // followStatus.style.display = 'block';
            //互相都关注的人
            //http://localhost:8080/api/user/getCommonInterest?interestId=1
            //发送请求
            const data = await fetch(`http://localhost/api/user/getCommonInterest?interestId=${uid}`, {
                mode: 'cors', // 明确请求模式
                headers: {
                    'Content-Type': 'application/json'
                }
            })
                .then(response => response.json())
                .then(data => {
                    // console.log(data);
                    return data.data;
                }
                )
                .catch(error => console.error('Error:', error));

            followStatus.textContent = '你们共同关注：' + data;
            followStatus.style.display = 'block';


        } else {
            followStatus.style.display = 'none';
        }
    } else {
        followBtn.textContent = '关注';
        followBtn.classList.remove('following');
        followStatus.style.display = 'none';
    }
}

// 渲染笔记列表
async function renderNotes() {
    notesList.innerHTML = '';

    //获取参数
    const params = new URLSearchParams(window.location.search);
    const uid = params.get('uid');
    // console.log(uid);

    // http://localhost:8080/api/note/listById?uid=1
    //发送请求
    const data = await fetch(`http://localhost/api/note/listById?uid=${uid}`, {
        mode: 'cors', // 明确请求模式
        headers: {
            'Content-Type': 'application/json'
        }
    })
        .then(response => response.json())
        .then(data => {
            // console.log(data);
            return data.data;
        }
        )
        .catch(error => console.error('Error:', error));

    notesData = data

    notesData.forEach(note => {
        const noteElement = createNoteElement(note);
        notesList.appendChild(noteElement);
    });
}

// 创建单个笔记元素
function createNoteElement(note) {
    const noteCard = document.createElement('div');
    noteCard.className = 'note-card';
    // <img src="${note.image}" alt="${note.title}" class="note-image">
    noteCard.innerHTML = `
        
        <div class="note-content">
            <h3 class="note-title">${note.title}</h3>
            <p class="note-excerpt">${note.content}</p>
            <div class="note-meta">
                <span>${note.likeCount} 赞</span>
                <span>创建日期：${formatDate(note.createdAt)}</span>
            </div>
        </div>
    `;

    return noteCard;
}

// 关注/取消关注事件
followBtn.addEventListener('click', function () {
    // 切换关注状态
    userData.isFollowing = !userData.isFollowing;

    // 更新粉丝数
    if (userData.isFollowing) {
        userData.stats.followers++;
    } else {
        userData.stats.followers--;
    }

    // 随机决定是否互相关注 (模拟)
    // if (userData.isFollowing && Math.random() > 0.5) {
    //     userData.isFollowedBack = true;
    // } else {
    //     userData.isFollowedBack = false;
    // }

    // 更新UI
    followerCount.textContent = userData.stats.followers;
    updateFollowButton();

    // 模拟API调用
    simulateApiCall();
});

// 模拟API调用
async function simulateApiCall() {
    // console.log(userData.isFollowing ? '已关注用户' : '已取消关注');
    // 实际项目中这里会是fetch或axios请求
    //获取参数
    const params = new URLSearchParams(window.location.search);
    const uid = params.get('uid');
    //http://localhost:8080/api/user/interestCOC?followingId=1
    //发送请求
    const data = await fetch(`http://localhost/api/user/interestCOC?followingId=${uid}`, {
        mode: 'cors', // 明确请求模式
        headers: {
            'Content-Type': 'application/json'
        }
    })
        .then(response => response.json())
        .then(data => {
            // console.log(data);
            return data.data;
        }
        )
        .catch(error => console.error('Error:', error));


}

// 初始化页面
initPage();